#!/bin/bash

# Conda 初始化修复脚本
# 用于修复 "conda activate" 错误

echo "========================================="
echo "Conda 初始化修复工具"
echo "========================================="

# 检测当前 shell
CURRENT_SHELL=$(basename "$SHELL")

echo "检测到当前 shell: $CURRENT_SHELL"

# 查找 conda
if [ -f "$HOME/miniconda/bin/conda" ]; then
    CONDA_PATH="$HOME/miniconda/bin/conda"
    echo "✓ 找到 Miniconda: $CONDA_PATH"
elif [ -f "$HOME/anaconda3/bin/conda" ]; then
    CONDA_PATH="$HOME/anaconda3/bin/conda"
    echo "✓ 找到 Anaconda: $CONDA_PATH"
elif command -v conda &> /dev/null; then
    CONDA_PATH=$(command -v conda)
    echo "✓ 找到 Conda: $CONDA_PATH"
else
    echo "✗ 未找到 Conda"
    echo "请先运行 deploy_qwen.sh 安装 Conda"
    exit 1
fi

# 将 conda 添加到 PATH（如果还没有）
export PATH="$(dirname "$CONDA_PATH"):$PATH"

# 检查是否已初始化
RC_FILE=""
if [ "$CURRENT_SHELL" = "bash" ]; then
    RC_FILE="$HOME/.bashrc"
elif [ "$CURRENT_SHELL" = "zsh" ]; then
    RC_FILE="$HOME/.zshrc"
else
    echo "⚠ 未识别的 shell，尝试初始化 bash 和 zsh"
    "$CONDA_PATH" init bash
    "$CONDA_PATH" init zsh
    echo ""
    echo "请运行以下命令之一："
    echo "  source ~/.bashrc  (bash 用户)"
    echo "  source ~/.zshrc   (zsh 用户)"
    exit 0
fi

if grep -q "conda initialize" "$RC_FILE" 2>/dev/null; then
    echo "✓ Conda 已在 $RC_FILE 中初始化"
else
    echo "正在初始化 Conda for $CURRENT_SHELL..."
    "$CONDA_PATH" init "$CURRENT_SHELL"
    echo ""
    echo "✓ Conda 初始化完成！"
    echo ""
    echo "请运行以下命令使更改生效："
    echo "  source $RC_FILE"
    echo ""
    echo "或者重新打开终端"
fi

echo ""
echo "========================================="
echo "快速激活 qwen314b 环境的方法："
echo "========================================="
echo ""
echo "方法 1 (推荐):"
echo "  source $RC_FILE"
echo "  conda activate qwen314b"
echo ""
echo "方法 2 (如果方法 1 不行):"
echo "  source $(dirname "$CONDA_PATH")/../etc/profile.d/conda.sh"
echo "  conda activate qwen314b"
echo ""
echo "方法 3 (直接使用完整路径):"
if [ -d "$HOME/miniconda/envs/qwen314b" ]; then
    echo "  export PATH=\"\$HOME/miniconda/envs/qwen314b/bin:\$PATH\""
    echo "  python --version  # 验证"
elif [ -d "$HOME/anaconda3/envs/qwen314b" ]; then
    echo "  export PATH=\"\$HOME/anaconda3/envs/qwen314b/bin:\$PATH\""
    echo "  python --version  # 验证"
fi
echo "========================================="

